Skip to main content

Matplotlib Tutorial: Core Concepts

Matplotlib is the most widely used plotting library in Python. It provides a MATLAB-like interface for creating static, animated, and interactive visualizations.

In this tutorial, we'll cover the core concepts of Matplotlib, including figures and axes, basic plot types, subplots, customization, and saving figures.


📥 Download the Sample Data

These datasets are used throughout the tutorial for hands-on plotting practice.

FileDescriptionLink
population_data.csvPopulation growth for 3 cities (2000–2024)Download
experiment_data.csvExperiment results with control & treatment groups (200 rows)Download

💡 Tip: Save these files to your working directory and load them with pd.read_csv() or np.loadtxt().


1. Introduction to Matplotlib

Matplotlib is designed around two main interfaces:

  • pyplot (plt): A state-based interface that mimics MATLAB's plotting commands
  • Object-oriented (OO) interface: Explicitly create figures and axes for fine-grained control

Key Features of Matplotlib:

  • Wide variety of plot types: Line, scatter, bar, histogram, contour, 3D, and more
  • Full customization: Colors, markers, line styles, fonts, ticks, labels
  • Publication-quality output: Save as PNG, PDF, SVG, EPS
  • Integration: Works with NumPy, Pandas, and Jupyter notebooks
  • Interactive: Zoom, pan, and save from the figure window

2. Installing Matplotlib

You can install Matplotlib via pip:

pip install matplotlib

3. Importing Matplotlib

import matplotlib.pyplot as plt
import numpy as np

This imports the pyplot interface as plt, which is the standard convention.


4. The Figure and Axes Architecture

In Matplotlib, every plot consists of:

  • Figure: The top-level container that holds all plot elements
  • Axes: The actual plotting area (what you draw on)
# Create a figure with a single axes
fig, ax = plt.subplots()

# Plot data on the axes
ax.plot([1, 2, 3], [4, 5, 6])

# Display the figure
plt.show()

5. Basic Line Plot

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True)
plt.show()

Multiple lines on the same plot

y2 = np.cos(x)

plt.plot(x, y, label='sin(x)')
plt.plot(x, y2, label='cos(x)')
plt.legend()
plt.show()

6. Scatter Plot

x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = np.random.rand(50) * 500

plt.scatter(x, y, c=colors, s=sizes, alpha=0.7, cmap='viridis')
plt.colorbar(label='Intensity')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Plot')
plt.show()

7. Bar Chart

categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]

plt.bar(categories, values, color='steelblue')
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Bar Chart')
plt.show()

# Horizontal bar chart
plt.barh(categories, values, color='coral')
plt.show()

8. Histogram

data = np.random.randn(1000)

plt.hist(data, bins=30, edgecolor='black', alpha=0.7)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()

9. Subplots

Using plt.subplots()

fig, axes = plt.subplots(2, 2, figsize=(10, 8))

x = np.linspace(0, 10, 100)

axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('sin(x)')

axes[0, 1].plot(x, np.cos(x), color='orange')
axes[0, 1].set_title('cos(x)')

axes[1, 0].plot(x, np.exp(-x / 3), color='green')
axes[1, 0].set_title('exp(-x/3)')

axes[1, 1].plot(x, x**2, color='red')
axes[1, 1].set_title('x²')

plt.tight_layout()
plt.show()

10. Customizing Plots

Colors, markers, and line styles

x = np.linspace(0, 10, 20)

plt.plot(x, x, 'r--') # red dashed line
plt.plot(x, x**2, 'bs') # blue squares
plt.plot(x, x**3, 'g^') # green triangles
plt.show()

Format strings: [color][marker][line]

CodeMeaning
r, g, b, c, m, y, k, wColors
o, s, ^, v, D, *, x, +Markers
-, --, -., :Line styles

Adding text and annotations

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.annotate('Peak', xy=(np.pi/2, 1), xytext=(np.pi/2, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.text(0, -1.5, 'y = sin(x)', fontsize=12, style='italic')
plt.show()

11. Working with Colors and Colormaps

# Named colors
plt.plot(x, y, color='firebrick')

# Hex colors
plt.plot(x, y, color='#FF5733')

# RGB tuples
plt.plot(x, y, color=(0.2, 0.4, 0.6))

# Colormaps for scatter/contour
x = np.random.rand(100)
y = np.random.rand(100)
c = np.random.rand(100)
plt.scatter(x, y, c=c, cmap='plasma')
plt.colorbar()
plt.show()

12. Saving Figures

plt.plot(x, y)
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
plt.savefig('plot.pdf', bbox_inches='tight')
plt.savefig('plot.svg', bbox_inches='tight')

13. Object-Oriented Interface

For more control, use the OO interface:

fig, ax = plt.subplots(figsize=(8, 4))

ax.plot(x, y, linewidth=2, color='navy')
ax.set_title('Object-Oriented Plot', fontsize=14)
ax.set_xlabel('x', fontsize=12)
ax.set_ylabel('y', fontsize=12)
ax.grid(True, alpha=0.3)
ax.set_xlim(0, 10)
ax.set_ylim(-1.5, 1.5)
ax.axhline(0, color='gray', linestyle='--', linewidth=0.5)

plt.tight_layout()
plt.show()

14. Common Plot Types

Pie chart

sizes = [30, 25, 20, 15, 10]
labels = ['A', 'B', 'C', 'D', 'E']
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.axis('equal')
plt.show()

Box plot

data = [np.random.randn(100) for _ in range(4)]
plt.boxplot(data, labels=['A', 'B', 'C', 'D'])
plt.show()

Contour plot

x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

plt.contourf(X, Y, Z, levels=20, cmap='viridis')
plt.colorbar()
plt.show()

Summary

Matplotlib is a powerful and flexible plotting library. Here's a recap of the key concepts we covered:

  • plt.figure() / plt.subplots(): Create figures and axes
  • plt.plot(): Line plots
  • plt.scatter(): Scatter plots
  • plt.bar() / plt.barh(): Bar charts
  • plt.hist(): Histograms
  • plt.subplots(): Multiple subplots
  • plt.savefig(): Save figures to file
  • Customization: Colors, markers, line styles, labels, legends, annotations
  • OO interface: fig, ax = plt.subplots() for fine-grained control